package com.esunny.httpclient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;

public class HttpClientService {

    private static final Log    log               = LogFactory.getLog(HttpClientService.class);

    /**
     * user_agent
     */
    private static final String USER_AGENT        = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11";

    /**
     * web im nginx server host and port
     */
    private String[]            hosts;

    /**
     * 最大连接数
     */
    private int                 maxConnections    = 5000;

    /**
     * 链接超时时间
     */
    private int                 connectionTimeout = 1000;

    /**
     * 每个主机最大连接数
     */
    private int                 maxPerRoute       = 500;

    /**
     * 读取超时时间
     */
    private int                 readTimeout       = 1000;

    /**
     * httpClient
     */
    private HttpClient          httpClient;

    public void init() {
        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager();
        manager.setMaxTotal(maxConnections);
        manager.setDefaultMaxPerRoute(maxPerRoute);

        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);

        DefaultHttpClient httpClient = new DefaultHttpClient(manager, params);
        this.httpClient = httpClient;
    }

    /**
     * http
     * 
     * @param requestUrl
     * @param httpBody
     * @return
     * @throws Exception
     */
    public boolean doPost(String requestUrl, String httpBody) throws Exception {
        // 拼装请求
        boolean result = false;
        HttpPost post = new HttpPost(requestUrl);
        post.addHeader("User-Agent", USER_AGENT);
        post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        StringEntity conent = new StringEntity(httpBody, "UTF-8");
        post.setEntity(conent);
        InputStream in = null;
        HttpResponse response = httpClient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();

        try {
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {

                result = true;
            } else {
                result = false;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                in = entity.getContent();
            }

        } finally {
            IOUtils.closeQuietly(in);
        }
        return result;
    }

    /**
     * http
     * 
     * @param requestUrl
     * @param httpBody
     * @return
     * @throws Exception
     */
    public String doGet(String requestUrl) throws Exception {

        HttpGet get = new HttpGet(requestUrl);
        InputStream in = null;
        StringBuffer sb = new StringBuffer();

        try {
            get.addHeader("User-Agent", USER_AGENT);
            get.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            // 处理响应
            HttpResponse response = httpClient.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            }
            if (entity != null) {
                in = entity.getContent();
                // BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                // String line = "";
                // while ((line = reader.readLine()) != null) {
                // sb.append(line);
                // }
                // return sb.toString();
            }

            return null;

        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    public void setMaxConnections(int maxConnections) {
        this.maxConnections = maxConnections;
    }

    public void setConnectionTimeout(int connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    public void setMaxPerRoute(int maxPerRoute) {
        this.maxPerRoute = maxPerRoute;
    }

    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }

    public static void main(String[] args) throws Exception {
       System.out.println(System.getProperty("user.dir"));
       
//        HttpClientService client = new HttpClientService();
//        client.setConnectionTimeout(1000);
//        client.setMaxConnections(10);
//        client.setMaxPerRoute(10);
//        client.setReadTimeout(1000);
//        client.init();
//        // client.doPost("http://192.168.1.62:6003/publish?", "1212");
//        // String sb = null;
//        for (int i = 0; i < 100; i++) {
//            client.doPost("http://192.168.1.62:6003/publish?", "1212");
//        }

        // System.out.println(sb);
    }
}
